<?php
class simplePagesEdit extends module {
	public $permissions = array('*'=>array(ROLE_ADMIN, ROLE_SUPERADMIN));
	public $title = "Simple editable pages (administration)";
	public $frame = "admin";
	
	public function run() {
		$query = "SELECT
			id,
			alias AS '"._("URL alias")."',
			title AS '"._("Title")."',
			date AS '"._("Edit date")."',
			published
			FROM simple_pages";
		new sqlTable($this, $query, $this->engine->getUrlParam(0));
		new pagination($this, $this->sql->totalRowsCount, $this->engine->getUrlParam(0));
	}
	
	public function delete() {
		$this->sql->deleteFromTable("simple_pages", array("id" => intval($this->engine->getUrlParam(0))));
		$this->engine->jump("/admin/simplePagesEdit/");
	}
	
	private function createForm($title) {
		$form = new formConstructor($this, "simplePage", "", $title);
		$form->addField("alias", _("URL alias"), new formString("/^[0-9a-zA-Z_]{1,30}$/"));
		$form->addField("title", _("Page title"), new formString("/^.{0,255}$/"));
		$form->addField("content", _("Content"), new formVisualEditor(80, 20));
		$form->addField(null, "Meta-Information", new formSeparator());
		$form->addField("keywords", _("Meta-keywords"), new formString("/^.{0,255}$/"));
		$form->addField("description", _("Meta-description"), new formString("/^.{0,255}$/"));
		$form->addField('published', _("Published"), new formRadio(array('yes'=>_("Yes"), 'no'=>_("No"))));
		$form->addField(null, _("Save"), new formSubmit());
		return $form;
	}
	
	public function createPage() {
		$form = $this->createForm(_("Create simple page"));
		if ($form->submit()) {
			if (count($form->errors) == 0) {
				try {
					$postData = $form->getAllValues();
					$postData['date'] = new sqlFunction("NOW()");

					$this->sql->insertIntoTable("simple_pages", $postData);
					$this->engine->jump("/admin/simplePagesEdit/");
				} catch (Exception $e) {
					new pageAlert($this, $e->getMessage());
				}
			} else {
				new pageAlert($this, _("Wrong form filling"));
			}
		} else {
			$form->setValue("published", "yes");
		}
		$form->write();
	}

	public function edit() {
		$form = $this->createForm(_("Edit simple page"));
		if ($form->submit()) {
			if (count($form->errors) == 0) {
				try {
					$postData = $form->getAllValues();
					$postData['date'] = new sqlFunction("NOW()");
					$this->sql->updateTable("simple_pages", $postData, array('id' => intval($this->engine->getUrlParam(0))));
					$this->engine->jump("/admin/simplePagesEdit/");
				} catch (Exception $e) {
					new pageAlert($this, $e->getMessage());
				}
			} else {
				new pageAlert($this, _("Wrong form filling"));
			}
		} else {
			$form->setValues($this->sql->getRowFromDB("SELECT title, keywords, description, alias, content, date, published FROM simple_pages WHERE id=".intval($this->engine->getUrlParam(0))));
		}
		$form->write();
	}
}
?>